package cn.weiron.fun.infrastructure.configuration;


import cn.weiron.fun.infrastructure.ErrorResponse;
import cn.weiron.fun.infrastructure.ResponseWrapper;
import cn.weiron.fun.infrastructure.dto.Response;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;

/**
 * <p>基础层：配置全局返回处理器</p>
 *
 * @author 马强
 */
@Configuration
public class CustomResponseWrapperConfig {
    @Bean("responseWrapper")
    public ResponseWrapper responseWrapper() {
        return new CustomResponseWrapper();
    }

    /**
     * 自定义返回包装器
     */
    public static class CustomResponseWrapper implements ResponseWrapper {
        @Override
        public boolean isObjectAfterWrap(Object object) {
            return (object instanceof Response);
        }

        @Override
        public Object wrap(String message, Object data) {
            //Leo Lee
            if (data instanceof String) {
                return data;
            }

            Response response = new Response();
            response.setCode(0);
            response.setMsg(message);

            // 分页数据处理
            if (data instanceof Page<?>) {
                Page<?> dataForPage = (Page<?>) data;
                response.setCount(dataForPage.getTotalElements());
                response.setData(dataForPage.getContent());
            }
            // 异常抛出数据处理
            else if (data instanceof ErrorResponse) {
                ErrorResponse errorResponse = (ErrorResponse) data;
                response.setCode(errorResponse.getStatus());
                response.setMsg(errorResponse.getMessage());
                response.setData(null);
            } else {
                response.setData(data);
            }

            return response;
        }

        @Override
        public Object wrap(String code, String message) {
            Response response = new Response();
            response.setCode(Integer.parseInt(code));
            response.setMsg(message);
            return response;
        }
    }
}